<?php declare(strict_types=1);

namespace think\msg\platform\dingtalk\convertor;

use think\msg\msg\RichTextMsg;
use think\msg\msg\TextMsg;
use think\msg\platform\dingtalk\dto\MarkdownRichTextMsgDto;
use think\msg\platform\dingtalk\dto\TextMsgDto;

class MsgConvertor
{
    public static function toTextMsgDto(TextMsg $msg): TextMsgDto
    {
        $textMsgDto = new TextMsgDto();
        $textMsgDto->setText($msg->getContent());
        return $textMsgDto;
    }

    public static function toRichTextMsgDto(RichTextMsg $msg): MarkdownRichTextMsgDto
    {
        $msgDto = new MarkdownRichTextMsgDto();
        $msgDto->setTitle($msg->getTitle());
        $contentList = $msg->getContent();
        $info = "# {$msg->getTitle()}\n\n";
        foreach ($contentList as $key => $content) {
            foreach ($content as $item) {
                if (0 === $key) {
                    // 第一行认为就是标题
                    $info .= "## {$item['text']}\n\n";
                } elseif ('a' === $item['tag']) {
                    $info .= "{$item['text']}\n\n";
                    $msgDto->setSingleTitle('查看详情');
                    $msgDto->setSingleUrl($item['url']);
                } elseif ('text' === $item['tag']) {
                    $info .= $item['text'] . "\n\n";
                }
            }
        }
        $msgDto->setText($info);
        return $msgDto;
    }
}